package com.pactera.integral.security.authentication;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;

/**
 * @author shilei
 * @Date 2017/6/9.
 */
public class TokenAuthenticationService {
    static final long EXPIRATIONTIME = 1000 * 60 * 60 * 24; // 1 days
    static final String SECRET = "ThisIsASecret";
    static final String TOKEN_PREFIX = "INTEGRAL";
    static final String HEADER_STRING = "Authorization";

    public static void addAuthentication(HttpServletResponse res, String username) {
        String JWT = Jwts.builder().setSubject(username).setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
    }

    public static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        if (StringUtils.hasText(token)) {
            // parse the token.
            String user = null;
            try {
                user = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody().getSubject();
            } catch (Exception e) {
                request.setAttribute("message", e.getMessage());
            }

            return user != null ? new UsernamePasswordAuthenticationToken(user, null) : null;
        }
        return null;
    }
}
